<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/26 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\admin\service\UploadFileService;
use app\common\controller\AdminBaseController;
use app\common\model\tang\MonthElectricityDegree as MerchantModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use app\common\model\tang\CostImportLog;
use think\Exception;
use think\facade\Session;

class ExportCenter extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\common\model\tang\MonthElectricityDegree();
        $this->LogModel = new CostImportLog();
    }

    public function index()
    {
        if (IS_AJAX) {
            $where = [];
            return $this->LogModel->getAdminPageData($this->param, 'id desc', $where);
        }
        return $this->fetch();
    }

    /**
     * 导入页面
     */
    public function detail()
    {
        return $this->fetch();
    }

    /**
     * 导入
     */
    public function import()
    {
        header("content-type:text/html;charset=utf-8");
        //上传excel文件
        $res = UploadFileService::instance()->setUploadPath('store/excel')->image('file');

        if ($res) {
            //获取上传到后台的文件名
            $fileName = $res['name'];
            //获取文件路径
            $filePath = app()->getRootPath() . 'public' . $res['thumb_path'];
            //获取文件后缀
            $suffix = $res['ext'];
            // 有Xls和Xlsx格式两种
            $reader = IOFactory::createReader('Xlsx');
        } else {
            return json(['status' => '1', 'message' => '文件过大或格式不正确导致上传失败-_-!']);
        }
//        $spreadsheet = $reader->load($filePath);

        //载入excel文件
//        $excel = $reader->load($filePath);
        $excel = IOFactory::load($filePath);

        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        $merchantModel = new \app\common\model\tang\Merchant();
        $import_data = []; //数组形式获取表格数据
        try {
            for ($i = 2; $i <= $row_num; $i++) {
                $data = [];
                $data['company'] = $excel->getActiveSheet()->getCell("A" . $i)->getValue();
                $data['code'] = $excel->getActiveSheet()->getCell("B" . $i)->getValue();
                $merchant_id = $merchantModel->where('code',$data['code'])->value('id');
                if(empty($merchant_id)){
                    throw new Exception('第'.$i.'行'. $data['code'].'未录入商户信息');
                }
                $data['userId'] = $excel->getActiveSheet()->getCell("C" . $i)->getValue();
                $data['pointId'] = $excel->getActiveSheet()->getCell("D" . $i)->getValue();
                $data['pointName'] = $excel->getActiveSheet()->getCell("E" . $i)->getValue();
                $data['type'] = $excel->getActiveSheet()->getCell("F" . $i)->getValue();
                $data['dataTime']  = $excel->getActiveSheet()->getCell("G" . $i)->getValue();
                if(is_numeric( $data['dataTime'])){
                     $data['dataTime'] = date('Y-m', \PHPExcel_Shared_Date::ExcelToPHP($excel->getActiveSheet()->getCell("G" . $i)->getValue()));
                }

                $data['rate'] = $excel->getActiveSheet()->getCell("H" . $i)->getValue();
                $data['fengStart'] = $excel->getActiveSheet()->getCell("I" . $i)->getValue();
                $data['fengEnd'] = $excel->getActiveSheet()->getCell("J" . $i)->getValue();
                $data['fengPower'] = $excel->getActiveSheet()->getCell("K" . $i)->getValue();
                $data['guStart'] = $excel->getActiveSheet()->getCell("L" . $i)->getValue();
                $data['guEnd'] = $excel->getActiveSheet()->getCell("M" . $i)->getValue();
                $data['guPower'] = $excel->getActiveSheet()->getCell("N" . $i)->getValue();
                $data['pingStart'] = $excel->getActiveSheet()->getCell("O" . $i)->getValue();
                $data['pingEnd'] = $excel->getActiveSheet()->getCell("P" . $i)->getValue();
                $data['pingPower'] = $excel->getActiveSheet()->getCell("Q" . $i)->getValue();
                $import_data[] = $data;
            }
        } catch (Exception $e) {
            return self::ajaxResult([], 0, 1, $e->getMessage());
        }
        $import_data = array_values($import_data);
        $count = count($import_data);
        $data['data'] = $import_data;
        $data['count'] = $count;
        return self::ajaxResult($data, 0, 0, 'success');
    }

    /**
     * @return 提交
     */
    public function add()
    {
        $input = file_get_contents('php://input');
        $param = json_decode($input,true);
        $param = $param['datas'];
        $model = new \app\common\model\tang\MonthElectricityDegree(); //峰谷平
        $danmodel = new \app\common\model\tang\MonthSoleElectricityLog(); //单一电价
        $success = [];
        $dan = [];
        $merchantModel = new \app\common\model\tang\Merchant();
        try {
            foreach ($param as $k => $v) {
                unset($v['LAY_TABLE_INDEX']);
                $merchant_id = $merchantModel->where('code',$v['code'])->value('id');
                $v['merchant_id'] = $merchant_id;
                $v['create_time'] = time();
                $v['pointId'] = trim($v['pointId']);
                $v['dataTime'] = trim($v['dataTime']);
                if($v['type']=='单一'){
                    $v['zongStart'] = $v['fengStart'];
                    $v['zongEnd'] = $v['fengEnd'];
                    $dan[] = $v;
                }else{
                    unset($v['code']);
                    unset($v['company']);
                    $success[] = $v;
                }
            }
            $model->saveAll($success);
            $danmodel->saveAll($dan);
            $CostImportLog['import_time'] = date('Y-m-d H:i:s', time());
            $CostImportLog['success_sum'] = count($param);
            $CostImportLog['fail_sum'] = 0;
            (new CostImportLog())->save($CostImportLog);
            return self::ajaxResult([], 0, 1, '导入成功');
        } catch (Exception $e) {
            return self::ajaxResult([], 0, 1, $e->getMessage());
        }

    }

    public function export()
    {
        $title = ['公司名称', '海鼎合同号', '华立老户号', '设备编号', '设备名称','单一/峰谷平', '月份', '倍率', '峰起始值', '峰止值', '峰用电量', '谷起值', '谷终值', '谷用电量', '平起值', '平终值', '平用电量'];
        return export_excel('电费数据模板_' . date('Y-m-d'), $title, []);
    }
}